#include "mqttwidget.h"
#include <QDateTime>
#include <QScrollBar>
#include <QDebug>

MqttWidget::MqttWidget(QWidget *parent)
    : QWidget(parent)
    , m_mqttManager(nullptr)
    , m_isConnected(false)
    , m_currentFanSpeed(0)
{
    // 创建业务层对象
    m_mqttManager = new MqttManager(this);
    
    // 初始化UI
    setupUI();
    connectSignals();
    loadDefaultConfig();
    updateUIState(false);
}

MqttWidget::~MqttWidget()
{
    if (m_mqttManager) {
        m_mqttManager->disconnectFromServer();
    }
}

/**
 * @brief 清理资源（返回主页时调用）
 */
void MqttWidget::cleanup()
{
    // 断开MQTT连接
    if (m_mqttManager && m_mqttManager->isConnected()) {
        m_mqttManager->disconnectFromServer();
        qDebug() << "MQTT测试：已断开连接";
    }
    
    qDebug() << "MQTT测试：资源清理完成";
}

void MqttWidget::setupUI()
{
    // 主布局 - 使用水平布局分为左右两栏，适配1024x600屏幕
    // 参考串口助手：顶部边距15px，左右边距15px
    QHBoxLayout *mainLayout = new QHBoxLayout(this);
    mainLayout->setSpacing(10);
    mainLayout->setContentsMargins(15, 60, 15, 10);  // 顶部留60px给返回按钮
    
    // ========== 左侧栏 ==========
    QWidget *leftWidget = new QWidget(this);
    QVBoxLayout *leftLayout = new QVBoxLayout(leftWidget);
    leftLayout->setSpacing(8);
    leftLayout->setContentsMargins(0, 0, 0, 0);
    
    // ========== 连接配置区 ==========
    m_connectionGroup = new QGroupBox("连接配置", leftWidget);
    m_connectionGroup->setMaximumHeight(155);  // 限制高度避免撑开
    QGridLayout *connectionLayout = new QGridLayout(m_connectionGroup);
    connectionLayout->setSpacing(8);
    connectionLayout->setContentsMargins(10, 12, 10, 10);
    
    // 第一行：服务器地址和端口
    QLabel *serverLabel = new QLabel("服务器:", this);
    serverLabel->setFixedWidth(55);
    connectionLayout->addWidget(serverLabel, 0, 0);
    
    m_serverEdit = new QLineEdit(this);
    m_serverEdit->setPlaceholderText("bemfa.com");
    m_serverEdit->setFixedHeight(28);
    m_serverEdit->setMinimumWidth(120);
    connectionLayout->addWidget(m_serverEdit, 0, 1);
    
    QLabel *portLabel = new QLabel("端口:", this);
    portLabel->setFixedWidth(40);
    connectionLayout->addWidget(portLabel, 0, 2);
    
    m_portSpinBox = new QSpinBox(this);
    m_portSpinBox->setRange(1, 65535);
    m_portSpinBox->setValue(8344);
    m_portSpinBox->setFixedHeight(28);
    m_portSpinBox->setFixedWidth(75);
    connectionLayout->addWidget(m_portSpinBox, 0, 3);
    
    // 第二行：用户私钥
    QLabel *uidLabel = new QLabel("私钥:", this);
    uidLabel->setFixedWidth(55);
    connectionLayout->addWidget(uidLabel, 1, 0);
    
    m_uidEdit = new QLineEdit(this);
    m_uidEdit->setPlaceholderText("用户UID");
    m_uidEdit->setFixedHeight(28);
    m_uidEdit->setEchoMode(QLineEdit::Password);  // 密码模式，隐藏显示
    connectionLayout->addWidget(m_uidEdit, 1, 1, 1, 3);
    
    // 第三行：连接按钮
    m_connectButton = new QPushButton("连接", this);
    m_connectButton->setFixedSize(130, 28);
    m_connectButton->setStyleSheet("QPushButton { background-color: #27ae60; color: white; font-weight: bold; }");
    connectionLayout->addWidget(m_connectButton, 2, 0, 1, 2);
    
    m_disconnectButton = new QPushButton("断开", this);
    m_disconnectButton->setFixedSize(130, 28);
    m_disconnectButton->setStyleSheet("QPushButton { background-color: #e74c3c; color: white; font-weight: bold; }");
    connectionLayout->addWidget(m_disconnectButton, 2, 2, 1, 2);
    
    // 添加间距行，避免按钮和状态重叠
    connectionLayout->setRowMinimumHeight(3, 5);
    
    // 第四行：状态显示
    QLabel *statusTextLabel = new QLabel("状态:", this);
    statusTextLabel->setFixedWidth(55);
    connectionLayout->addWidget(statusTextLabel, 4, 0);
    
    m_statusLabel = new QLabel("○ 未连接", this);
    m_statusLabel->setStyleSheet("color: #95a5a6; font-weight: bold; font-size: 11px;");
    connectionLayout->addWidget(m_statusLabel, 4, 1, 1, 3);
    
    // 错误标签（放在GroupBox外面）
    m_errorLabel = new QLabel("", this);
    m_errorLabel->setStyleSheet("QLabel { background-color: #e74c3c; color: white; padding: 5px; border-radius: 3px; font-size: 11px; }");
    m_errorLabel->setWordWrap(true);
    m_errorLabel->setVisible(false);  // 默认隐藏
    m_errorLabel->setMaximumHeight(30);
    
    leftLayout->addWidget(m_connectionGroup);
    leftLayout->addWidget(m_errorLabel);  // 错误提示紧跟在连接配置后面
    
    // ========== 主题配置区 ==========
    m_topicGroup = new QGroupBox("主题配置", leftWidget);
    m_topicGroup->setMaximumHeight(70);
    QHBoxLayout *topicLayout = new QHBoxLayout(m_topicGroup);
    topicLayout->setSpacing(8);
    topicLayout->setContentsMargins(10, 10, 10, 10);
    
    QLabel *fanLabel = new QLabel("风扇:", this);
    fanLabel->setFixedWidth(40);
    topicLayout->addWidget(fanLabel);
    
    m_fanTopicEdit = new QLineEdit(this);
    m_fanTopicEdit->setPlaceholderText("fan001");
    m_fanTopicEdit->setFixedHeight(28);
    topicLayout->addWidget(m_fanTopicEdit);
    
    QLabel *tempLabel = new QLabel("温度:", this);
    tempLabel->setFixedWidth(40);
    topicLayout->addWidget(tempLabel);
    
    m_tempTopicEdit = new QLineEdit(this);
    m_tempTopicEdit->setPlaceholderText("temp001");
    m_tempTopicEdit->setFixedHeight(28);
    topicLayout->addWidget(m_tempTopicEdit);
    
    // 保存配置按钮（隐藏，主题配置一般不需要保存）
    m_saveConfigButton = new QPushButton("保存", this);
    m_saveConfigButton->setVisible(false);
    
    leftLayout->addWidget(m_topicGroup);
    
    // ========== 设备控制区 ==========
    m_controlGroup = new QGroupBox("风扇控制", leftWidget);
    m_controlGroup->setMaximumHeight(110);
    QVBoxLayout *controlLayout = new QVBoxLayout(m_controlGroup);
    controlLayout->setSpacing(8);
    controlLayout->setContentsMargins(10, 10, 10, 10);
    
    // 模式和档位在同一行
    QHBoxLayout *fanControlLayout = new QHBoxLayout();
    fanControlLayout->setSpacing(10);
    
    m_autoModeRadio = new QRadioButton("自动", this);
    m_manualModeRadio = new QRadioButton("手动", this);
    m_modeButtonGroup = new QButtonGroup(this);
    m_modeButtonGroup->addButton(m_autoModeRadio, 0);
    m_modeButtonGroup->addButton(m_manualModeRadio, 1);
    m_autoModeRadio->setChecked(true);
    fanControlLayout->addWidget(m_autoModeRadio);
    fanControlLayout->addWidget(m_manualModeRadio);
    fanControlLayout->addSpacing(10);
    
    m_fanSpeed0Button = new QPushButton("S0", this);
    m_fanSpeed1Button = new QPushButton("S1", this);
    m_fanSpeed2Button = new QPushButton("S2", this);
    m_fanSpeed3Button = new QPushButton("S3", this);
    m_fanSpeed0Button->setFixedSize(60, 30);
    m_fanSpeed1Button->setFixedSize(60, 30);
    m_fanSpeed2Button->setFixedSize(60, 30);
    m_fanSpeed3Button->setFixedSize(60, 30);
    m_fanSpeed0Button->setToolTip("关闭");
    m_fanSpeed1Button->setToolTip("低速");
    m_fanSpeed2Button->setToolTip("中速");
    m_fanSpeed3Button->setToolTip("高速");
    fanControlLayout->addWidget(m_fanSpeed0Button);
    fanControlLayout->addWidget(m_fanSpeed1Button);
    fanControlLayout->addWidget(m_fanSpeed2Button);
    fanControlLayout->addWidget(m_fanSpeed3Button);
    controlLayout->addLayout(fanControlLayout);
    
    // 当前档位显示
    m_currentSpeedLabel = new QLabel("当前: S0 (关闭)", this);
    m_currentSpeedLabel->setStyleSheet("font-weight: bold; font-size: 11px; color: #27ae60;");
    m_currentSpeedLabel->setAlignment(Qt::AlignCenter);
    controlLayout->addWidget(m_currentSpeedLabel);
    
    leftLayout->addWidget(m_controlGroup);
    
    // ========== 温度控制区 ==========
    m_temperatureGroup = new QGroupBox("温度数据", leftWidget);
    m_temperatureGroup->setMaximumHeight(90);
    QGridLayout *tempLayout = new QGridLayout(m_temperatureGroup);
    tempLayout->setSpacing(8);
    tempLayout->setContentsMargins(10, 10, 10, 10);
    
    QLabel *publishLabel = new QLabel("发布:", this);
    publishLabel->setFixedWidth(40);
    tempLayout->addWidget(publishLabel, 0, 0);
    
    m_temperatureSpinBox = new QSpinBox(this);
    m_temperatureSpinBox->setRange(-50, 150);
    m_temperatureSpinBox->setSuffix(" °C");
    m_temperatureSpinBox->setValue(25);
    m_temperatureSpinBox->setFixedHeight(28);
    tempLayout->addWidget(m_temperatureSpinBox, 0, 1);
    
    m_publishTempButton = new QPushButton("发布", this);
    m_publishTempButton->setFixedSize(60, 28);
    tempLayout->addWidget(m_publishTempButton, 0, 2);
    
    QLabel *receiveLabel = new QLabel("接收:", this);
    receiveLabel->setFixedWidth(40);
    tempLayout->addWidget(receiveLabel, 1, 0);
    
    m_receivedTempLabel = new QLabel("-- °C", this);
    m_receivedTempLabel->setStyleSheet("font-size: 14px; font-weight: bold; color: #3498db;");
    tempLayout->addWidget(m_receivedTempLabel, 1, 1, 1, 2);
    
    leftLayout->addWidget(m_temperatureGroup);
    
    // ========== 统计信息区 ==========
    m_statisticsGroup = new QGroupBox("统计", leftWidget);
    m_statisticsGroup->setMaximumHeight(60);
    QHBoxLayout *statsLayout = new QHBoxLayout(m_statisticsGroup);
    statsLayout->setSpacing(10);
    statsLayout->setContentsMargins(10, 8, 10, 8);
    
    m_sentCountLabel = new QLabel("发: 0", this);
    m_sentCountLabel->setStyleSheet("font-size: 11px; color: #3498db; font-weight: bold;");
    m_receivedCountLabel = new QLabel("收: 0", this);
    m_receivedCountLabel->setStyleSheet("font-size: 11px; color: #27ae60; font-weight: bold;");
    m_clearStatsButton = new QPushButton("清空统计", this);
    m_clearStatsButton->setFixedHeight(26);
    
    statsLayout->addWidget(m_sentCountLabel);
    statsLayout->addSpacing(10);
    statsLayout->addWidget(m_receivedCountLabel);
    statsLayout->addStretch();
    statsLayout->addWidget(m_clearStatsButton);
    
    leftLayout->addWidget(m_statisticsGroup);
    
    // ========== 右侧栏 - 消息收发区 ==========
    QWidget *rightWidget = new QWidget(this);
    QVBoxLayout *rightLayout = new QVBoxLayout(rightWidget);
    rightLayout->setSpacing(8);
    rightLayout->setContentsMargins(0, 0, 0, 0);
    
    m_messageGroup = new QGroupBox("消息收发", rightWidget);
    QVBoxLayout *messageLayout = new QVBoxLayout(m_messageGroup);
    messageLayout->setSpacing(8);
    messageLayout->setContentsMargins(10, 10, 10, 10);
    
    // 接收区标题
    QHBoxLayout *receiveHeaderLayout = new QHBoxLayout();
    receiveHeaderLayout->setSpacing(5);
    QLabel *receiveMsgLabel = new QLabel("接收消息", this);
    receiveMsgLabel->setStyleSheet("font-weight: bold; font-size: 12px;");
    receiveHeaderLayout->addWidget(receiveMsgLabel);
    receiveHeaderLayout->addStretch();
    m_clearReceiveButton = new QPushButton("清空", this);
    m_clearReceiveButton->setFixedSize(60, 26);
    receiveHeaderLayout->addWidget(m_clearReceiveButton);
    messageLayout->addLayout(receiveHeaderLayout);
    
    // 接收文本区域
    m_receiveTextEdit = new QTextEdit(this);
    m_receiveTextEdit->setReadOnly(true);
    m_receiveTextEdit->setFixedHeight(280);  // 固定高度280px，避免和发送区重叠
    m_receiveTextEdit->setStyleSheet("QTextEdit { font-size: 11px; line-height: 1.3; }");
    messageLayout->addWidget(m_receiveTextEdit);
    
    // 发送区
    QLabel *sendLabel = new QLabel("发送消息", this);
    sendLabel->setStyleSheet("font-weight: bold; font-size: 12px;");
    messageLayout->addWidget(sendLabel);
    
    QGridLayout *sendLayout = new QGridLayout();
    sendLayout->setSpacing(8);
    
    QLabel *topicLabel = new QLabel("主题:", this);
    topicLabel->setFixedWidth(45);
    sendLayout->addWidget(topicLabel, 0, 0);
    
    m_topicEdit = new QLineEdit(this);
    m_topicEdit->setPlaceholderText("输入主题名称");
    m_topicEdit->setFixedHeight(28);
    sendLayout->addWidget(m_topicEdit, 0, 1);
    
    QLabel *msgLabel = new QLabel("消息:", this);
    msgLabel->setFixedWidth(45);
    sendLayout->addWidget(msgLabel, 1, 0);
    
    m_messageEdit = new QLineEdit(this);
    m_messageEdit->setPlaceholderText("输入消息内容");
    m_messageEdit->setFixedHeight(28);
    sendLayout->addWidget(m_messageEdit, 1, 1);
    
    QHBoxLayout *sendBtnLayout = new QHBoxLayout();
    m_sendButton = new QPushButton("发送", this);
    m_sendButton->setFixedSize(100, 28);
    m_sendButton->setStyleSheet("QPushButton { background-color: #3498db; color: white; font-weight: bold; }");
    m_clearSendButton = new QPushButton("清空", this);
    m_clearSendButton->setFixedSize(70, 28);
    sendBtnLayout->addWidget(m_sendButton);
    sendBtnLayout->addWidget(m_clearSendButton);
    sendBtnLayout->addStretch();
    sendLayout->addLayout(sendBtnLayout, 2, 0, 1, 2);
    
    messageLayout->addLayout(sendLayout);
    
    rightLayout->addWidget(m_messageGroup);
    
    // 添加左右两栏到主布局（左侧400px，右侧占剩余空间）
    mainLayout->addWidget(leftWidget);
    leftWidget->setFixedWidth(400);
    mainLayout->addWidget(rightWidget, 1);
    
    setLayout(mainLayout);
}

void MqttWidget::connectSignals()
{
    // UI控件信号连接
    connect(m_connectButton, &QPushButton::clicked, this, &MqttWidget::onConnect);
    connect(m_disconnectButton, &QPushButton::clicked, this, &MqttWidget::onDisconnect);
    connect(m_sendButton, &QPushButton::clicked, this, &MqttWidget::onSendMessage);
    connect(m_clearReceiveButton, &QPushButton::clicked, this, &MqttWidget::onClearReceive);
    connect(m_clearSendButton, &QPushButton::clicked, this, &MqttWidget::onClearSend);
    connect(m_clearStatsButton, &QPushButton::clicked, this, &MqttWidget::onClearStatistics);
    
    // 模式切换
    connect(m_autoModeRadio, &QRadioButton::toggled, this, &MqttWidget::onModeChanged);
    connect(m_manualModeRadio, &QRadioButton::toggled, this, &MqttWidget::onModeChanged);
    
    // 风扇档位按钮
    connect(m_fanSpeed0Button, &QPushButton::clicked, this, &MqttWidget::onFanSpeedButtonClicked);
    connect(m_fanSpeed1Button, &QPushButton::clicked, this, &MqttWidget::onFanSpeedButtonClicked);
    connect(m_fanSpeed2Button, &QPushButton::clicked, this, &MqttWidget::onFanSpeedButtonClicked);
    connect(m_fanSpeed3Button, &QPushButton::clicked, this, &MqttWidget::onFanSpeedButtonClicked);
    
    // 温度发布
    connect(m_publishTempButton, &QPushButton::clicked, this, &MqttWidget::onPublishTemperature);
    
    // 业务层信号连接
    connect(m_mqttManager, &MqttManager::connected, this, &MqttWidget::onConnected);
    connect(m_mqttManager, &MqttManager::disconnected, this, &MqttWidget::onDisconnected);
    connect(m_mqttManager, &MqttManager::errorOccurred, this, &MqttWidget::onError);
    connect(m_mqttManager, &MqttManager::messageReceived, this, &MqttWidget::onMessageReceived);
    connect(m_mqttManager, &MqttManager::rawDataReceived, this, &MqttWidget::onRawDataReceived);
    connect(m_mqttManager, &MqttManager::connectionStatusChanged, this, &MqttWidget::onConnectionStatusChanged);
    connect(m_mqttManager, &MqttManager::statisticsUpdated, this, &MqttWidget::onStatisticsUpdated);
    
    // 设备状态信号连接
    connect(m_mqttManager, &MqttManager::fanModeChanged, this, &MqttWidget::onFanModeChanged);
    connect(m_mqttManager, &MqttManager::fanSpeedChanged, this, &MqttWidget::onFanSpeedChanged);
    connect(m_mqttManager, &MqttManager::temperatureReceived, this, &MqttWidget::onTemperatureReceived);
}

void MqttWidget::updateUIState(bool connected)
{
    m_isConnected = connected;
    
    // 连接配置控件
    m_serverEdit->setEnabled(!connected);
    m_portSpinBox->setEnabled(!connected);
    m_uidEdit->setEnabled(!connected);
    m_connectButton->setEnabled(!connected);
    m_disconnectButton->setEnabled(connected);
    
    // 主题配置
    m_fanTopicEdit->setEnabled(!connected);
    m_tempTopicEdit->setEnabled(!connected);
    m_saveConfigButton->setEnabled(!connected);
    
    // 设备控制
    m_autoModeRadio->setEnabled(connected);
    m_manualModeRadio->setEnabled(connected);
    m_fanSpeed0Button->setEnabled(connected);
    m_fanSpeed1Button->setEnabled(connected);
    m_fanSpeed2Button->setEnabled(connected);
    m_fanSpeed3Button->setEnabled(connected);
    
    // 温度控制
    m_temperatureSpinBox->setEnabled(connected);
    m_publishTempButton->setEnabled(connected);
    
    // 消息发送
    m_topicEdit->setEnabled(connected);
    m_messageEdit->setEnabled(connected);
    m_sendButton->setEnabled(connected);
}

MqttConfig MqttWidget::getConfigFromUI() const
{
    MqttConfig config;
    config.serverHost = m_serverEdit->text().trimmed();
    config.serverPort = m_portSpinBox->value();
    config.uid = m_uidEdit->text().trimmed();
    config.fanTopic = m_fanTopicEdit->text().trimmed();
    config.tempTopic = m_tempTopicEdit->text().trimmed();
    
    return config;
}

void MqttWidget::loadDefaultConfig()
{
    m_serverEdit->setText("bemfa.com");
    m_portSpinBox->setValue(8344);
    m_uidEdit->setText("6bef66d76d5240d5ab9ca165973a4096");
    m_fanTopicEdit->setText("fan001");
    m_tempTopicEdit->setText("temp001");
}

// UI控件槽函数实现

void MqttWidget::onConnect()
{
    MqttConfig config = getConfigFromUI();
    
    // 验证配置
    if (config.serverHost.isEmpty()) {
        m_errorLabel->setText("错误: 服务器地址不能为空");
        return;
    }
    
    if (config.uid.isEmpty()) {
        m_errorLabel->setText("错误: 用户UID不能为空");
        return;
    }
    
    m_errorLabel->clear();
    
    // 连接到服务器
    if (m_mqttManager->connectToServer(config)) {
        m_receiveTextEdit->append(QString("[%1] 正在连接到 %2:%3...")
            .arg(QDateTime::currentDateTime().toString("hh:mm:ss"))
            .arg(config.serverHost)
            .arg(config.serverPort));
    }
}

void MqttWidget::onDisconnect()
{
    m_mqttManager->disconnectFromServer();
    m_receiveTextEdit->append(QString("[%1] 断开连接")
        .arg(QDateTime::currentDateTime().toString("hh:mm:ss")));
}

void MqttWidget::onSendMessage()
{
    QString topic = m_topicEdit->text().trimmed();
    QString message = m_messageEdit->text().trimmed();
    
    if (topic.isEmpty() || message.isEmpty()) {
        m_errorLabel->setText("错误: 主题和消息不能为空");
        return;
    }
    
    m_errorLabel->clear();
    
    if (m_mqttManager->publishMessage(topic, message)) {
        m_receiveTextEdit->append(QString("[%1] 发送 -> 主题:%2 消息:%3")
            .arg(QDateTime::currentDateTime().toString("hh:mm:ss"))
            .arg(topic)
            .arg(message));
    }
}

void MqttWidget::onClearReceive()
{
    m_receiveTextEdit->clear();
}

void MqttWidget::onClearSend()
{
    m_topicEdit->clear();
    m_messageEdit->clear();
}

void MqttWidget::onClearStatistics()
{
    m_mqttManager->clearStatistics();
}

void MqttWidget::onModeChanged(bool checked)
{
    if (!checked || !m_isConnected) {
        return;
    }
    
    bool manual = m_manualModeRadio->isChecked();
    m_mqttManager->setFanMode(manual);
}

void MqttWidget::onFanSpeedButtonClicked()
{
    if (!m_isConnected) {
        return;
    }
    
    QPushButton *button = qobject_cast<QPushButton*>(sender());
    int speed = 0;
    
    if (button == m_fanSpeed0Button) speed = 0;
    else if (button == m_fanSpeed1Button) speed = 1;
    else if (button == m_fanSpeed2Button) speed = 2;
    else if (button == m_fanSpeed3Button) speed = 3;
    
    m_mqttManager->setFanSpeed(speed);
}

void MqttWidget::onPublishTemperature()
{
    if (!m_isConnected) {
        return;
    }
    
    double temp = m_temperatureSpinBox->value();
    m_mqttManager->publishTemperature(temp);
}

// 业务层信号槽函数实现

void MqttWidget::onConnected()
{
    updateUIState(true);
    m_statusLabel->setText("● 已连接");
    m_statusLabel->setStyleSheet("color: #27ae60; font-weight: bold; font-size: 11px;");
    m_errorLabel->setVisible(false);
    
    m_receiveTextEdit->append(QString("[%1] ✓ 连接成功")
        .arg(QDateTime::currentDateTime().toString("hh:mm:ss")));
}

void MqttWidget::onDisconnected()
{
    updateUIState(false);
    m_statusLabel->setText("○ 未连接");
    m_statusLabel->setStyleSheet("color: #95a5a6; font-weight: bold; font-size: 11px;");
    
    m_receiveTextEdit->append(QString("[%1] ✗ 连接断开")
        .arg(QDateTime::currentDateTime().toString("hh:mm:ss")));
}

void MqttWidget::onError(const QString &error)
{
    m_errorLabel->setText("⚠ 错误: " + error);
    m_errorLabel->setVisible(true);
    
    m_receiveTextEdit->append(QString("[%1] ✗ 错误: %2")
        .arg(QDateTime::currentDateTime().toString("hh:mm:ss"))
        .arg(error));
}

void MqttWidget::onMessageReceived(const QString &topic, const QString &msg)
{
    m_receiveTextEdit->append(QString("[%1] 收到 <- 主题:%2 消息:%3")
        .arg(QDateTime::currentDateTime().toString("hh:mm:ss"))
        .arg(topic)
        .arg(msg));
    
    // 自动滚动到底部
    QScrollBar *scrollBar = m_receiveTextEdit->verticalScrollBar();
    scrollBar->setValue(scrollBar->maximum());
}

void MqttWidget::onRawDataReceived(const QString &data)
{
    // 可以选择显示原始数据，或者只在调试时显示
    // m_receiveTextEdit->append(QString("[RAW] %1").arg(data));
}

void MqttWidget::onConnectionStatusChanged(const QString &status)
{
    m_statusLabel->setText("状态: " + status);
}

void MqttWidget::onStatisticsUpdated(quint64 sent, quint64 received)
{
    m_sentCountLabel->setText(QString("发送: %1").arg(sent));
    m_receivedCountLabel->setText(QString("接收: %1").arg(received));
}

void MqttWidget::onFanModeChanged(bool manual)
{
    // 更新UI显示当前模式
    if (manual) {
        m_manualModeRadio->setChecked(true);
    } else {
        m_autoModeRadio->setChecked(true);
    }
    
    m_receiveTextEdit->append(QString("[%1] 模式切换: %2")
        .arg(QDateTime::currentDateTime().toString("hh:mm:ss"))
        .arg(manual ? "手动模式 (M1)" : "自动模式 (M0)"));
}

void MqttWidget::onFanSpeedChanged(int speed)
{
    m_currentFanSpeed = speed;
    
    QString speedText;
    switch (speed) {
        case 0: speedText = "S0 (关闭)"; break;
        case 1: speedText = "S1 (低速)"; break;
        case 2: speedText = "S2 (中速)"; break;
        case 3: speedText = "S3 (高速)"; break;
        default: speedText = "未知"; break;
    }
    
    m_currentSpeedLabel->setText("当前档位: " + speedText);
    
    m_receiveTextEdit->append(QString("[%1] 风扇档位: %2")
        .arg(QDateTime::currentDateTime().toString("hh:mm:ss"))
        .arg(speedText));
}

void MqttWidget::onTemperatureReceived(double temp)
{
    m_receivedTempLabel->setText(QString::number(temp, 'f', 1) + " °C");
    
    m_receiveTextEdit->append(QString("[%1] 温度数据: %2 °C")
        .arg(QDateTime::currentDateTime().toString("hh:mm:ss"))
        .arg(temp, 0, 'f', 1));
}

